import "./App.css";
import React, { useState } from "react";
import InfiniteScroll from "react-infinite-scroll-component";

const ACCESS_KEY = "Ip0XA55zY7b7-d19osq1L5btGg-YCeDZVpnnJjXqHxs";

function App() {
  const [img, setImg] = useState("");
  const [res, setRes] = useState([]);
  const [page, setPage] = useState(1);
  const [isLoading, setIsLoading] = useState(false);
  const [selectedImage, setSelectedImage] = useState(null); // для попапа
  const [noResults, setNoResults] = useState(false); // нет результатов

  const fetchRequest = async () => {
    try {
      setIsLoading(true);
      const response = await fetch(
        `https://api.unsplash.com/search/photos?page=${page}&query=${img}&client_id=${ACCESS_KEY}&per_page=30&orientation=squarish`,
      );
      if (!response.ok) {
        throw new Error("Network response was not ok");
      }
      const data = await response.json();
      if (data.results && Array.isArray(data.results)) {
        const result = data.results;
        setRes((prevRes) => [...prevRes, ...result]);
        setPage((prevPage) => prevPage + 1);
        setNoResults(result.length === 0);
      } else {
        console.error("Invalid data format received from the API");
      }
      setIsLoading(false);
    } catch (error) {
      console.error("Error fetching data:", error);
      setIsLoading(false);
    }
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    if (img.trim() === "") {
      return; // если пустое поле ввода, не делаем запрос
    }
    setRes([]); // очистить существующие результаты
    setPage(1); // сбросить номер страницы
    fetchRequest();
  };

  return (
    <>
      <div className={"container"}>
        <form className="submit" onSubmit={handleSubmit}>
          <input
            className="submit"
            type="search"
            placeholder="Телефоны, яблоки, груши..."
            value={img}
            onChange={(e) => setImg(e.target.value)}
          />
          <button type="submit" className="btn">
            Искать
          </button>
        </form>
        <InfiniteScroll
          dataLength={res.length}
          next={fetchRequest}
          hasMore={true}
          loader={isLoading ? <h4>Loading...</h4> : null}
          endMessage={
            <p style={{ textAlign: "center" }}>
              <b>Yay! You have seen it all</b>
            </p>
          }
        >
          <div className="image-list">
            {res.map((val, index) => (
              <img
                key={`${val.id}-${index}`}
                className="img"
                src={val.urls.small}
                alt={val.alt_description}
                onClick={() => setSelectedImage(val.urls.full)}
              />
            ))}
          </div>
        </InfiniteScroll>

        {/*Popup*/}
        {selectedImage && (
          <div className="popup" onClick={() => setSelectedImage(null)}>
            <img
              src={selectedImage}
              alt="Selected Image"
              className="popup-image"
            />
            <span
              className="close-icon"
              onClick={() => setSelectedImage(null)}
            />
          </div>
        )}

        {noResults && <p>К сожалению, поиск не дал результатов :(</p>}
      </div>
    </>
  );
}

export default App;
